import React, { useState, useEffect } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/pages/OnboardAndLeave/AdjustPost/Add/Wrap.less';
import { Card, Col, Form, Row, Spin, Button, message, Modal } from 'antd';
import pageTabUtil from '@/utils/pageTabUtil';
import moment from 'moment';
import { connect } from 'umi';
import {
    formatLeaveFormDate,
    formatOvertimeFormData,
    formatVacationCancelFormData,
    formatInstitutionFormData
} from '@/pages/WorkFlow/Flow/utils';
import { useRequest } from '@/hooks';
import { BottomAction } from '@/components';
import { readStatusMap, useSetReadStatus } from '@/hooks/useSetReadStatus';
import { useBeforeSubmit } from '@/pages/WorkFlow/hooks';

import { getProcessIsBlocked } from './services';

import Step from '../components/Step';
import FormList from '../components/JsonToForm';
import style from './index.less';
import { ApproveModal } from './components';
import { objMomentFormat, getSummary } from '../../utils';

const Detail = ({ dispatch, flowWaitApproval, location, form, loading, user }) => {
    const { employeeCode } = user;
    const listLoading = loading;
    const [approveLoading, setApproveLoading] = useState(false);
    const { detailData = {}, processList, canReturnList } = flowWaitApproval;
    const { taskId, processInstanceName = detailData.processInstanceName, createUser } = location.query;
    const { formList, formValueMap, status, currentCandidateFlag } = detailData;

    // 审批按钮loading;
    const [buttonLoading, setButtonLoading] = useState({
        returnBtn: false,
        rejectBtn: false,
        agreeBtn: false
    });

    // 审批按钮状态
    const [buttonStatus, setButtonStatus] = useState({
        returnBtn: true,
        rejectBtn: true,
        agreeBtn: true
    });

    const [extra, setExtra] = useState({
        taskId,
        employeeCode
    });

    useSetReadStatus({ id: extra.processInstanceId, type: readStatusMap.APPLY });

    const [visible, setVisible] = useState(false);
    const [approveData, setApproveData] = useState({});

    const fetchDetail = () => {
        const params = { taskId };
        dispatch({
            type: 'flowWaitApproval/fetchDetail',
            payload: params,
            callback: res => {
                if (res.code === 10000) {
                    const { processInstanceId, processDefinitionId, taskDefinitionKey } = res.data.taskInfo;
                    setExtra({ ...extra, processInstanceId, processDefinitionId, taskDefinitionKey });

                    // 前端判断是否是交接流程审批节点，是的话隐藏拒绝按钮
                    if (res.data?.formList.find(item => item.formId.includes('Handover'))) {
                        setButtonStatus({ ...buttonStatus, rejectBtn: false });
                    }
                }
            }
        });
    };
    // 审批流程节点
    const fetchProcessList = () => {
        const params = {
            processInstanceId: extra.processInstanceId
        };
        dispatch({
            type: 'flowWaitApproval/fetchProcess',
            payload: params
        });
    };

    // 判断流程是否阻塞
    const { run: fetchProcessIsBlocked } = useRequest(value => getProcessIsBlocked(value), {
        manual: true,
        onSuccess: res => {
            const { data, code, msg } = res;
            setButtonLoading({
                returnBtn: false,
                rejectBtn: false,
                agreeBtn: false
            });
            if (code === 10000) {
                if (data && data?.waitBussDealwith) {
                    Modal.warning({
                        title: '提示',
                        content: data?.waitBussDealwithRemark
                    });
                } else {
                    setVisible(true);
                }
            } else {
                message.error(msg);
            }
        }
    });

    // 页面卸载时清空数据
    useEffect(
        () => () => {
            dispatch({
                type: 'flowWaitApproval/resetState',
                payload: {
                    processList: [],
                    detailData: {}
                }
            });
        },
        []
    );

    const { handleBeforeSubmit } = useBeforeSubmit(formList?.[0]?.tag);

    const handleSubmit = args => {
        const { title, values: modalValues = {} } = args;
        const { reason, targetNode } = modalValues;
        // 提交前的参数进行预处理
        const values = handleBeforeSubmit(form.getFieldsValue());
        const formValues = objMomentFormat(values);

        switch (title) {
            case '审批同意':
                form.validateFields(errors => {
                    if (!errors) {
                        let copyFormValues = formValues;

                        // 请假 form data 特殊处理
                        if (Object.keys(formValues).includes('leaveType')) {
                            copyFormValues = formatLeaveFormDate(formValues);
                        }

                        // 加班特殊处理
                        if (Object.keys(formValues).includes('overTimeType')) {
                            copyFormValues = formatOvertimeFormData(formValues);
                        }

                        // 处理出差
                        if (Object.keys(formValues).includes('businessTripTotalExpense')) {
                            copyFormValues = formatLeaveFormDate(formValues);
                        }

                        // 处理销假
                        if (Object.keys(formValues).includes('vacationSelect')) {
                            copyFormValues = formatVacationCancelFormData(formValues);
                        }

                        // 外出数据特殊处理
                        if (
                            Object.keys(formValues).includes('durationOrigin') &&
                            Object.keys(formValues).includes('duration')
                        ) {
                            copyFormValues = {
                                ...copyFormValues,
                                duration: copyFormValues.durationOrigin,
                                startTime: moment(copyFormValues.startTime).format('YYYY-MM-DD HH:mm:00'),
                                endTime: moment(copyFormValues.endTime).format('YYYY-MM-DD HH:mm:00')
                            };
                        }

                        // 制度实施范围
                        if (
                            Object.keys(formValues).includes('scope') &&
                            Object.keys(formValues).includes('institutionNo')
                        ) {
                            copyFormValues = formatInstitutionFormData(formValues);
                        }

                        const [applicationAbstract, applicationAbstractArr] = getSummary(formList, copyFormValues); // 生成摘要

                        setApproveLoading(true);
                        dispatch({
                            type: 'flowWaitApproval/fetchAgree',
                            payload: {
                                ...extra,
                                reason: reason || '',
                                formDatasJson: JSON.stringify({ ...formValueMap, ...copyFormValues }),
                                applicationAbstract,
                                applicationAbstractArr
                            },
                            callback: async res => {
                                if (res.code === 10000) {
                                    await setVisible(false);
                                    message.success(res.msg);
                                    pageTabUtil.closeTab();
                                } else {
                                    message.error(res.msg);
                                }
                                setApproveLoading(false);
                            }
                        });
                    } else {
                        setVisible(false);
                        message.error('请先填写必填项');
                    }
                });
                break;
            case '审批拒绝':
                setApproveLoading(true);
                dispatch({
                    type: 'flowWaitApproval/fetchRefuse',
                    payload: {
                        ...extra,
                        reason
                    },
                    callback: async res => {
                        if (res.code === 10000) {
                            await setVisible(false);
                            message.success(res.msg);
                            pageTabUtil.closeTab();
                        } else {
                            message.error(res.msg);
                        }
                        setApproveLoading(false);
                    }
                });
                break;
            case '审批退回':
                setApproveLoading(true);
                console.log({
                    taskId: extra.taskId,
                    processInstanceId: extra.processInstanceId,
                    taskDefinitionKey: extra.taskDefinitionKey,
                    targetNode,
                    reason
                });
                dispatch({
                    type: 'flowWaitApproval/fetchReturn',
                    payload: {
                        taskId: extra.taskId,
                        processInstanceId: extra.processInstanceId,
                        taskDefinitionKey: extra.taskDefinitionKey,
                        targetNode,
                        reason,
                        formDatasJson: JSON.stringify({ ...formValueMap })
                    },
                    callback: async res => {
                        if (res.code === 10000) {
                            await setVisible(false);
                            message.success(res.msg);
                            pageTabUtil.closeTab();
                        } else {
                            message.error(res.msg);
                        }
                        setApproveLoading(false);
                    }
                });
                break;
            default:
                break;
        }
        return null;
    };

    useEffect(() => {
        // 页面首次加载先清空models数据
        dispatch({
            type: 'flowWaitApproval/save',
            payload: {
                processList: [],
                detailData: {}
            }
        });
        fetchDetail();
    }, []);

    useEffect(() => {
        if (extra.processInstanceId) {
            fetchProcessList();
        }
    }, [extra]);

    return (
        <PageHeaderWrapper type="success">
            <Spin spinning={listLoading}>
                <Card>
                    <div
                        style={{
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            display: 'flex',
                            height: '60px',
                            paddingBottom: '16px',
                            borderBottom: '1px solid rgba(237,237,237,1)'
                        }}
                    >
                        <div>
                            <h3 className={styles.title}>{processInstanceName}</h3>
                        </div>
                        {/* 判断是否有审批的流程 */}
                        {currentCandidateFlag === 1 ? (
                            <div style={{ textAlign: 'right' }}>
                                <div style={{ display: status === 1 ? 'none' : 'block' }}>
                                    <BottomAction>
                                        {buttonStatus.returnBtn && canReturnList.length > 0 && (
                                            <Button
                                                style={{ marginRight: '8px' }}
                                                loading={buttonLoading.returnBtn}
                                                onClick={() => {
                                                    // 设置loading
                                                    setButtonLoading({
                                                        returnBtn: true,
                                                        rejectBtn: false,
                                                        agreeBtn: false
                                                    });
                                                    fetchProcessIsBlocked(extra.processInstanceId);
                                                    setApproveData({
                                                        title: '审批退回',
                                                        label: '退回原因',
                                                        placeholder: '请输入退回意见',
                                                        required: true,
                                                        canReturnList
                                                    });
                                                }}
                                            >
                                                退回
                                            </Button>
                                        )}
                                        {buttonStatus.rejectBtn && (
                                            <Button
                                                style={{ marginRight: '8px' }}
                                                loading={buttonLoading.rejectBtn}
                                                onClick={() => {
                                                    // 设置loading
                                                    setButtonLoading({
                                                        returnBtn: false,
                                                        rejectBtn: true,
                                                        agreeBtn: false
                                                    });
                                                    fetchProcessIsBlocked(extra.processInstanceId);
                                                    setApproveData({
                                                        title: '审批拒绝',
                                                        label: '拒绝原因',
                                                        placeholder: '请输入拒绝意见',
                                                        required: true
                                                    });
                                                }}
                                            >
                                                拒绝
                                            </Button>
                                        )}
                                        {buttonStatus.agreeBtn && (
                                            <Button
                                                type="primary"
                                                loading={buttonLoading.agreeBtn}
                                                onClick={() => {
                                                    // 设置loading
                                                    setButtonLoading({
                                                        returnBtn: true,
                                                        rejectBtn: false,
                                                        agreeBtn: true
                                                    });
                                                    fetchProcessIsBlocked(extra.processInstanceId);
                                                    setApproveData({
                                                        title: '审批同意',
                                                        label: '同意意见',
                                                        placeholder: '同意',
                                                        required: false
                                                    });
                                                }}
                                            >
                                                同意
                                            </Button>
                                        )}
                                    </BottomAction>
                                </div>
                            </div>
                        ) : null}
                    </div>
                    <div className={style.detailCtr}>
                        <FormList
                            form={form}
                            formList={formList}
                            submitBtn="确定"
                            createUser={createUser}
                            formValueMap={formValueMap}
                            approve={processList}
                            status={detailData?.status}
                            currentCandidateFlag={currentCandidateFlag}
                            processInstanceId={extra.processInstanceId}
                        />
                        <div className={styles.wrap}>
                            <h3 className={styles.title}>审批流程</h3>
                            <Row style={{ marginLeft: 30 }}>
                                <Col offset={3}>
                                    <Step data={processList} />
                                </Col>
                            </Row>
                        </div>
                    </div>
                </Card>
            </Spin>

            <ApproveModal
                visible={visible}
                data={approveData}
                confirmLoading={approveLoading}
                onOk={e => {
                    handleSubmit(e);
                }}
                onCancel={() => {
                    setVisible(false);
                }}
            />
        </PageHeaderWrapper>
    );
};
export default connect(({ flowWaitApproval, loading, user }) => ({
    flowWaitApproval,
    loading: loading.effects['flowWaitApproval/fetchDetail'],
    user: user.currentUser
}))(Form.create()(Detail));
